package com.zpark.user_system.controller;

import com.zpark.user_system.bean.User;
import com.zpark.user_system.service.IUserService;
import com.zpark.user_system.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户控制层
 */
@WebServlet("/user/user_login.do")
public class UserController extends HttpServlet {

    private IUserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户登录数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 调用service对应方法处理登录业务
        User user = userService.login(username, password);

        // 判断是否登录成功
        if (user == null) {
            request.setAttribute("msg", "用户名或者错误");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
        }else {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            // 重定向到登录成功页面
            response.sendRedirect(request.getContextPath() + "/jsp/main.jsp");
        }

    }
}
